package com.qianbei.user.person;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.ext.HttpCallback;
import com.android.volley.ext.RequestInfo;
import com.bumptech.glide.Glide;
import com.qianbei.R;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.rxbus.RxBus;
import com.qianbei.common.utilis.Permission;
import com.qianbei.common.utilis.img.CanmlTools;
import com.qianbei.common.utilis.img.CropCircleTransformation;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class PersonalInformationActivity extends BaseActivity implements View.OnClickListener, CanmlTools.CamerCallback {

    private ImageView mIvPersonalHead;
    private LinearLayout mLlPerHead;
    private TextView mTvPersonalName;
    private LinearLayout mLlPerName;
    private TextView mTvPersonalPhone;
    private String userID;
    private CanmlTools canmlTools;
    private ProgressDialog upDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_information);
        initView();

        setTitle("个人中心");
        userID = SetData.getUserID();
        canmlTools = new CanmlTools(mContext, this);
        upDialog = new ProgressDialog(mContext);// .showProgress("正在上传");

        intGetData();
    }

    private void intGetData() {
        ServerControl sc = new ServerControl(Request.Method.GET, GET_PERSONAL_INFO + userID + "?");

        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    PersonBean personBean = JSON.parseObject(sr.bodyData.toString(), PersonBean.class);

                    String mobile = personBean.getData().getMobile();
                    String headimg = personBean.getData().getHeadimg();
                    String username = personBean.getData().getUsername();

                    String maskNumber = mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length());
                    mTvPersonalPhone.setText(maskNumber);
                    mTvPersonalName.setText(username);
                    if(!((BaseActivity) mContext).isFinishing()) {
                        Glide.with(mContext)
                                .load(headimg)
                                .bitmapTransform(new CropCircleTransformation(mContext))
                                .placeholder(R.drawable.ic_launcher)
                                .into(mIvPersonalHead);
                    }

                }
            }
        };

        sc.startVolley();
    }

    public void initView() {
        mIvPersonalHead = (ImageView) findViewById(R.id.iv_personal_head);
        mLlPerHead = (LinearLayout) findViewById(R.id.ll_per_head);
        mTvPersonalName = (TextView) findViewById(R.id.tv_personal_name);
        mLlPerName = (LinearLayout) findViewById(R.id.ll_per_name);
        mTvPersonalPhone = (TextView) findViewById(R.id.tv_personal_phone);

        mLlPerHead.setOnClickListener(this);
        mLlPerName.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_per_head:
                checkPermission(v);
                break;
            case R.id.ll_per_name:
                Intent intent = new Intent(mContext, UpdateNameActivity.class);
                intent.putExtra("nickName", mTvPersonalName.getText().toString());
                startActivityForResult(intent, 232);
                break;
        }
    }

    /**
     * android 6.0运行时权限检查
     *
     * @param v
     */
    public void checkPermission(View v) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA},
                        Permission.WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
            } else {
                canmlTools.showCanmel(v.getId(), 2);
            }

        } else {
            canmlTools.showCanmel(v.getId(), 2);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 232:
                RxBus.getDefault().post("userinfo");
                intGetData();
                break;
        }
        canmlTools.onresult(requestCode, data);
    }

    @Override
    public void camerPickphoto(String imageUri, int i) {
        switch (i) {

            case R.id.ll_per_head:
//                mHeadUrl = imageUri;
                if (!((BaseActivity) mContext).isFinishing()) {
                    Glide.with(this).load(imageUri)
                            .bitmapTransform(new CropCircleTransformation(mContext))
                            .placeholder(R.drawable.ic_launcher)
                            .into(mIvPersonalHead);
                }
                upLoadImage(imageUri, new HttpCall(0));
                break;
        }
    }

    public class HttpCall implements HttpCallback {

        private int id;

        public HttpCall(int id) {
            this.id = id;
        }

        @Override
        public void onStart() {

        }

        @Override
        public void onResult(String string) {

            try {
                JSONObject jsonObject = new JSONObject(string);
                if (Integer.parseInt(jsonObject.optString("status")) == 1) {

                    new MsgAlert().show(jsonObject.optString("msg"));
                    String imgurl = jsonObject.optJSONObject("data").optString("headimg");
                    SetData.setHeadImg(imgurl);
                    RxBus.getDefault().post("userinfo");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onLoading(long count, long current) {

        }

        @Override
        public void onFinish() {
            upDialog.close();
        }

        @Override
        public void onError(Exception e) {

        }

        @Override
        public void onCancelled() {

        }
    }

    /**
     * 上传图片
     */
    private void upLoadImage(String imgData, HttpCallback back) {
        ServerControl sr = new ServerControl();

        Map<String, Object> params = new HashMap<String, Object>();

        if (imgData != null) {
            params.put("uid", userID);
            params.put("file", new File(imgData));
        }

        RequestInfo requestInfo = new RequestInfo();
        requestInfo.url = UPLOAD_IMG;
        requestInfo.putAllParams(params);
        sr.upload(requestInfo, back);
        upDialog.showProgress("正在上传");
    }

}
